﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Data;
using TciNewsReader_2014_04.Model;
namespace TciNewsReader_2014_04
{
    public partial class ViewModel
    {
        public ObservableCollection<ExceptionInfo> ExceptionInfos { get; private set; }
        private ListCollectionView _exceptionsListCollectionView;
        private void InitialiseExceptions()
        {
            ExceptionInfos = new ObservableCollection<ExceptionInfo>();
            _exceptionsListCollectionView = CollectionViewSource.GetDefaultView(ExceptionInfos) as ListCollectionView;
        }
        private void AddExceptions(FeedInfo feedInfo)
        {
            if (feedInfo.IncludeInView)
            {
                if (_exceptionsListCollectionView != null)
                {
                    foreach (Exception ex in feedInfo.Exceptions)
                    {
                        string culprit = feedInfo.FeedPublisherName;
                        if (String.IsNullOrEmpty(culprit))
                        {
                            culprit = feedInfo.Url;
                        }
                        Exception ex1 = ex;
                        _exceptionsListCollectionView.Dispatcher.Invoke(() => _exceptionsListCollectionView.AddNewItem(new ExceptionInfo {Culprit = culprit, Message = ex1.Message}));
                    }
                    _exceptionsListCollectionView.CommitNew();
                }
            }
        }
    }
    public class ExceptionInfo : INotifyPropertyChanged
    {
        private string _culprit;
        public string Culprit
        {
            [DebuggerStepThrough]
            get { return _culprit; }
            [DebuggerStepThrough]
            set
            {
                if (value != _culprit)
                {
                    _culprit = value;
                    OnPropertyChanged("Culprit");
                }
            }
        }
        private string _message;
        public string Message
        {
            [DebuggerStepThrough]
            get { return _message; }
            [DebuggerStepThrough]
            set
            {
                if (value != _message)
                {
                    _message = value;
                    OnPropertyChanged("Message");
                }
            }
        }
        #region INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string name)
        {
            var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion

    }
}
